import json
import os
import time
import re


class Video_utils:
    sourceDirectory = ''
    targetDirectory = ''
    counter = 0

    def __init__(self, source, target) -> None:
        self.sourceDirectory = source
        self.targetDirectory = target
        self.counter = 0

    def transfer(self):
        if self.sourceDirectory == '' or self.targetDirectory == '':
            return Result(False, '资源文件是空的')
        self.transVideo(self.sourceDirectory)
        return Result(True, '转换结束, 成功转换文件{}个'.format(self.counter))

    def transVideo(self, path):
        # 递归文件找到entry.json
        # 首先遍历当前目录所有文件及文件夹
        file_list = os.listdir(path)
        # 准备循环判断每个元素是否是文件夹还是文件，是文件的话，把名称传入list，是文件夹的话，递归
        for file in file_list:
            # 利用os.path.join()方法取得路径全名，并存入cur_path变量，否则每次只能遍历一层目录
            cur_path = os.path.join(path, file)
            # 判断是否是文件夹
            if os.path.isdir(cur_path):
                self.transVideo(cur_path)
            else:
                # all_files.append(file)
                # show
                # print(file)
                if file == 'entry.json':
                    self.create_video(cur_path, path)

    # 读取json文件中的信息并生成文件
    def create_video(self, file_path, path):
        with open(file_path, 'r', encoding='utf8') as js:
            entry_data = json.load(js)
            # print(entry_data)
            # 下级文件夹名
            type_tag = entry_data['type_tag']
            # title = entry_data['title']
            title = entry_data['page_data']['part']

            # title = title.replace('|', '-').replace(' ', '')
            # 替换windows文件名不支持的字符
            invalidWinStr = r'\\|/|:|\*|\?|"|<|>|\|| +'
            title = re.sub(invalidWinStr, '-', title)

            # 音视频文件
            tmp_path = os.path.join(path, type_tag)
            video_path = os.path.join(tmp_path, 'video.m4s')
            audio_path = os.path.join(tmp_path, 'audio.m4s')

            output_file = os.path.join(self.targetDirectory, title + '.mp4')

            # 重名则在名字后加上当前毫秒时间戳
            if os.path.isfile(output_file):
                print('文件名重复: 该文件名为: {}'.format(output_file))
                output_file = os.path.join(self.targetDirectory, title + str(time.time()) + '.mp4')

            print(output_file)

            # 调用ffmpeg合成视频
            cmd = 'ffmpeg -i {} -i {} -codec copy {}'.format(video_path, audio_path, output_file)

            if not os.getcwd().endswith('ffmpeg'):
                os.chdir('ffmpeg')
            try:
                os.system(cmd)
                # 计数
                self.counter += 1
            except:
                pass
            time.sleep(0.1)


# 返回结果
class Result:
    success = True
    message = 'everything is all right!'

    def __init__(self, success, message):
        self.success = success
        self.message = message
